<template>
  <view class="product-detail-page" :style="{ paddingTop: statusBarHeight + 'px' }">
    <!-- 自定义导航栏 -->
    <view class="custom-navbar" :style="{ paddingTop: statusBarHeight + 'px' }">
      <view class="navbar-content">
        <view class="back-btn" @tap="goBack">
          <text class="iconfont">←</text>
        </view>
        <text class="navbar-title">商品详情</text>
        <view class="more-btn">
          <text class="iconfont">⋯</text>
        </view>
      </view>
    </view>

    <scroll-view class="content-scroll" scroll-y :style="{ paddingTop: (statusBarHeight + 88) + 'rpx' }">
      <!-- 商品图片 -->
      <view class="product-image-container">
        <image :src="productInfo.image" mode="widthFix" class="product-image"></image>
      </view>
      
      <!-- 商品信息 -->
      <view class="product-info-section">
        <view class="product-header">
          <text class="product-name">{{ productInfo.name }}</text>
          <view class="product-price-row">
            <text class="current-price">¥ {{ productInfo.price }}</text>
            <text v-if="productInfo.originalPrice" class="original-price">¥ {{ productInfo.originalPrice }}</text>
          </view>
        </view>
        
        <view class="product-meta">
          <view class="meta-item">
            <text class="meta-label">销量</text>
            <text class="meta-value">{{productInfo.sales}}</text>
          </view>
          <view class="meta-item">
            <text class="meta-label">库存</text>
            <text class="meta-value">{{productInfo.stock}}</text>
          </view>
          <view class="meta-item">
            <text class="meta-label">评价</text>
            <text class="meta-value">{{productInfo.rating}}分</text>
          </view>
        </view>
      </view>
      
      <!-- 商品详情 -->
      <view class="product-detail-section">
        <view class="section-title">商品详情</view>
        <view class="detail-content">
          <text class="detail-text">{{ productInfo.description }}</text>
        </view>
      </view>
      
      <!-- 商品评价 -->
      <view class="product-reviews-section">
        <view class="section-title">用户评价 ({{ reviews.length }})</view>
        <view class="reviews-list">
          <view class="review-item" v-for="(review, index) in reviews" :key="index">
            <view class="review-header">
              <image :src="review.avatar" mode="aspectFill" class="review-avatar"></image>
              <view class="review-user-info">
                <text class="review-username">{{ review.username }}</text>
                <view class="review-stars">
                  <text class="star" v-for="i in 5" :key="i" :class="{ 'filled': i <= review.rating }">★</text>
                </view>
              </view>
              <text class="review-time">{{ review.time }}</text>
            </view>
            <text class="review-content">{{ review.content }}</text>
          </view>
        </view>
      </view>
    </scroll-view>
    
    <!-- 底部操作栏 -->
    <view class="bottom-actions">
      <view class="action-item" @tap="toggleFavorite">
        <text class="iconfont" :class="{ 'active': productInfo.isFavorite }">
          {{ productInfo.isFavorite ? '❤️' : '🤍' }}
        </text>
        <text class="action-text">收藏</text>
      </view>
      <view class="action-item" @tap="addToCart">
        <text class="iconfont">🛒</text>
        <text class="action-text">购物车</text>
      </view>
      <view class="buy-now-btn" @tap="buyNow">
        <text class="btn-text">立即购买</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import userManager from '@/common/utils/user.js'
import systemUtils from '@/common/utils/system.js'
import {getProductDetail ,
		getProductReviews,
		addFavorite, 
		removeFavorite, 
		isFavorite,
		addToCartFromFavorite} from '@/api/Productapi.js'
// import { getUserInfo } from '@/common/utils/user.js'

const statusBarHeight = ref(0)
const productInfo = ref({
  id: null,
  name: '',
  price: null,
  originalPrice: null,
  image: '',
  isFavorite: false,
  description: '',
  sales:null,
  stock:null,
  rating:null
})

const reviews = ref([])

// 页面加载时获取状态栏高度
onMounted(() => {
  statusBarHeight.value = systemUtils.getStatusBarHeight()
})

onLoad((options) => {
  // 如果有传入的商品ID，可以根据ID获取商品详情
  if (!options.id) {
    uni.showToast({ title: '缺少商品ID', icon: 'none' })
    return
  }
  uni.showLoading({ title: '加载中...' })
  loadProductData(options.id)
})

const loadProductData = async(id) => {
	if (!userManager.checkLogin()) {
	    // 如果未登录，isFavorite 为 false
	    productInfo.value.isFavorite = false;
	  }
	
try {
	const userId = userManager.user.userId;
    // 并行请求：商品详情、评价、收藏状态（如果已登录）
    const detailPromise = getProductDetail(id);
        const reviewsPromise = getProductReviews(id);
        const favoritePromise = userId ? isFavorite(userId, id) : Promise.resolve(false);
    
        const [detailRes, reviewsRes, favoriteStatus] = await Promise.all([
          detailPromise,
          reviewsPromise,
          favoritePromise
        ]);
	// 填充商品信息
    if (detailRes) {
      //映射后端字段到前端模型
      productInfo.value = {
        id: detailRes.productId,
        name: detailRes.name,
        price: detailRes.price,
        originalPrice: detailRes.originalPrice || null,
        image: detailRes.image || '/static/images/default-product.png',
        isFavorite: Boolean(favoriteStatus), // 转布尔值
        description: detailRes.description || '暂无商品描述',
		sales:detailRes.sales,
		stock:detailRes.stock,
		rating:detailRes.rating
      }
    } else {
      uni.showToast({ title: '商品不存在', icon: 'none' })
    }
	
	// 填充评价列表
	if (Array.isArray(reviewsRes)) {
	    // 映射后端字段到前端模型
	    reviews.value = reviewsRes.map(review => ({
	      avatar: review.avatarUrl || '/static/images/user-avatar.png', // 使用后端返回头像
	      username: review.nickname || '匿名用户', // 使用后端返回昵称
	      rating: review.grade, // 评分
	      time: formatTime(review.createTime), // 格式化时间
	      content: review.description // 评论内容
	    }));
	}
	
  } catch (error) {
    uni.showToast({ title: '加载失败', icon: 'none' })
    console.error('加载商品详情出错:', error)
  }finally{
	uni.hideLoading()
  }
}

// 时间格式化工具函数（可选）
const formatTime = (timestamp) => {
  if (!timestamp) return '';
  const date = new Date(timestamp);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
};

//返回
const goBack = () => {
  uni.navigateBack()
}

// 检查登录状态的函数
const checkLogin = () => {
  if (!userManager.checkLogin()) {
    uni.showModal({
      title: '提示',
      content: '该功能需要登录后使用，是否前往登录？',
      confirmText: '去登录',
      cancelText: '取消',
      success: function (res) {
        if (res.confirm) {
          // 跳转到"我的"页面
          uni.switchTab({
            url: '/pages/mine/mine'
          })
        }
      }
    })
    return false
  }
  return true
}

const toggleFavorite = async () => {
  // 检查登录
  if (!checkLogin()) return;

  const userId = userManager.user.userId;
  const productId = productInfo.value.id;
  if (!userId || !productId) {
    uni.showToast({ title: '参数异常', icon: 'none' });
    return;
  }

  uni.showLoading({ title: '处理中...' });

  try {
    let success = false;
    if (productInfo.value.isFavorite) {
      // 已收藏 → 取消收藏
      success = await removeFavorite(userId, productId);
      if (success) {
        productInfo.value.isFavorite = false;
        uni.showToast({ title: '已取消收藏', icon: 'success' });
      }
    } else {
      // 未收藏 → 添加收藏
      success = await addFavorite(userId, productId);
      if (success) {
        productInfo.value.isFavorite = true;
        uni.showToast({ title: '收藏成功', icon: 'success' });
      }
    }

    if (!success) {
      // 操作失败，不改变状态
      uni.showToast({ title: '操作失败，请重试', icon: 'none' });
    }

  } catch (error) {
    console.error('收藏操作失败:', error);
    uni.showToast({ title: '网络错误', icon: 'none' });
  } finally {
    uni.hideLoading();
  }
};

const addToCart = async () => {
  // 检查登录状态
  if (!checkLogin()) return
  console.log("商品：",productInfo.value);
  const userId = userManager.user.userId;
  await addToCartFromFavorite(userId,productInfo.value.id)
  uni.showToast({ title: '加购成功', icon: 'success' });
}

const buyNow = () => {
  // 检查登录状态
  if (!checkLogin()) return
  uni.navigateTo({
    url: '/pages/confirm/buyNowConfirm/buyNowConfirm?product=' + encodeURIComponent(JSON.stringify(productInfo.value))
  })
}
</script>

<style scoped>
.product-detail-page {
  min-height: 100vh;
  background-color: #F5F5F5;
}

/* 自定义导航栏 */
.custom-navbar {
  background: linear-gradient(135deg, #89CFF0 0%, #B7F0AD 100%);
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
}

.navbar-content {
  height: 88rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 32rpx;
}

.back-btn,
.more-btn {
  width: 64rpx;
  height: 64rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 36rpx;
  color: #FFFFFF;
}

.navbar-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #FFFFFF;
}

/* 内容区域 */
.content-scroll {
  height: 100vh;
  padding-bottom: 120rpx;
}

/* 商品图片 */
.product-image-container {
  width: 100%;
  background-color: #FFFFFF;
}

.product-image {
  width: 100%;
}

/* 商品信息 */
.product-info-section {
  background-color: #FFFFFF;
  margin: 24rpx 32rpx;
  border-radius: 24rpx;
  padding: 32rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
}

.product-header {
  margin-bottom: 24rpx;
}

.product-name {
  font-size: 36rpx;
  font-weight: bold;
  color: #333333;
  display: block;
  margin-bottom: 16rpx;
}

.product-price-row {
  display: flex;
  align-items: baseline;
  gap: 16rpx;
}

.current-price {
  font-size: 48rpx;
  font-weight: bold;
  color: #89CFF0;
}

.original-price {
  font-size: 28rpx;
  color: #999999;
  text-decoration: line-through;
}

.product-meta {
  display: flex;
  justify-content: space-between;
  padding-top: 24rpx;
  border-top: 1rpx solid #F0F0F0;
}

.meta-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.meta-label {
  font-size: 24rpx;
  color: #999999;
  margin-bottom: 8rpx;
}

.meta-value {
  font-size: 28rpx;
  font-weight: 500;
  color: #333333;
}

/* 商品详情 */
.product-detail-section {
  background-color: #FFFFFF;
  margin: 24rpx 32rpx;
  border-radius: 24rpx;
  padding: 32rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333333;
  margin-bottom: 24rpx;
}

.detail-content {
  line-height: 1.6;
}

.detail-text {
  font-size: 28rpx;
  color: #555555;
}

/* 商品评价 */
.product-reviews-section {
  background-color: #FFFFFF;
  margin: 24rpx 32rpx;
  border-radius: 24rpx;
  padding: 32rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
}

.reviews-list {
  padding-bottom: 24rpx;
}

.review-item {
  margin-bottom: 32rpx;
}

.review-item:last-child {
  margin-bottom: 0;
}

.review-header {
  display: flex;
  align-items: center;
  margin-bottom: 16rpx;
}

.review-avatar {
  width: 64rpx;
  height: 64rpx;
  border-radius: 50%;
  margin-right: 16rpx;
}

.review-user-info {
  flex: 1;
}

.review-username {
  font-size: 28rpx;
  font-weight: 500;
  color: #333333;
  display: block;
  margin-bottom: 8rpx;
}

.review-stars {
  display: flex;
}

.star {
  font-size: 24rpx;
  color: #CCCCCC;
}

.star.filled {
  color: #FFD700;
}

.review-time {
  font-size: 24rpx;
  color: #999999;
}

.review-content {
  font-size: 28rpx;
  color: #555555;
  line-height: 1.5;
}

/* 底部操作栏 */
.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #FFFFFF;
  padding: 24rpx 32rpx;
  display: flex;
  align-items: center;
  box-shadow: 0 -4rpx 16rpx rgba(0, 0, 0, 0.08);
}

.action-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  font-size: 24rpx;
  color: #999999;
  margin-right: 32rpx;
}

.action-item .iconfont.active {
  color: #FF3B30;
}

.action-text {
  margin-top: 8rpx;
}

.buy-now-btn {
  flex: 1;
  height: 80rpx;
  background: linear-gradient(135deg, #89CFF0 0%, #B7F0AD 100%);
  border-radius: 999rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.btn-text {
  font-size: 32rpx;
  font-weight: bold;
  color: #FFFFFF;
}
</style>